package heap;

public class Heap01 {
    public static void sort(int[] arr){
        int len = arr.length;
        //构建大顶堆
        for (int i = (len - 1 ) / 2; i >= 0; i--) {
            heapify(arr, i, len);
        }
        for (int i = len - 1; i >= 0 ; i--) {
            System.out.println(arr[0]);
            swap(arr,i,0);
            heapify(arr,0,i);
        }
    }

    public static void heapify(int arr[],int now,int len){
        int left = 2 * now + 1;
        int right = 2 * now + 2;
        int maxIndex = now;
        if(left < len  && arr[left] > arr[maxIndex]){
            maxIndex = left;
        }
        if(right < len  && arr[right] > arr[maxIndex]){
            maxIndex = right;
        }
        if(maxIndex != now){
            swap(arr,maxIndex,now);
            heapify(arr,maxIndex,len);
        }
    }

    public static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
